import React from 'react';
import {connect} from 'dva/index';
import {Button, DatePicker, Drawer, Form, Input, Popconfirm, Select, Table} from 'antd';
import styles from '../index.less';


import ViewTitle from '../../components/ViewTitle';
import FormBase from '../../components/Base/FormBase';
import notify from "../../components/NotificationExtra";
import {FormField, ModalView, SearchForm} from 'antd-extra';
import moment from 'moment';
import 'moment/locale/zh-cn';
import ModalCreateOrEditCustomer from "./modals/ModalCreateOrEditCustomer";
import ModalCustomerDetail from "./modals/ModalCustomerDetail";

moment.locale('zh-cn');
const {RangePicker} = DatePicker;
const _ = require('lodash');
const {Option} = Select;
const table = 'Customer';
const title = '客户';

@Form.create()
@connect(({user, global, dynamicLabel, customer}) => ({...user, ...global, ...customer, ...dynamicLabel}))
export default class Index extends FormBase {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    const {dispatch} = this.props;
    const payload = this.props.form.getFieldsValue();
    _.map(payload, (value, key) => {
      console.log('procure find payload', value);
      if (value === '') {
        payload[key] = undefined;
      }
    });
    let {name, code, phone} = payload;


    /**
     * 输入框清除之后会成为 ”“
     * @type {undefined}
     */
    name = name === '' ? undefined : name;
    phone = phone === '' ? undefined : phone;
    code = code === '' ? undefined : code;

    dispatch && dispatch({
      type: 'global/getModel',
      payload: {table}
    });

    this.props.dispatch({
      type: 'customer/findMany',
      payload: {name, code, phone}
    });

  }

  columns = () => {
    const model = this.props[`${table}Model`];
    if (!model) return [];
    const {labels = []} = model;
    let temp = [
      {
        title: '客户编码',
        dataIndex: 'code',
        key: 'code'
      },
      {
        title: '客户名称',
        dataIndex: 'name',
        key: 'name'
      },
      {
        title: '行业',
        dataIndex: 'industry',
        key: 'industry'
      }

    ];
    const temp1 = labels.length ? this.getDynamicLabelCols(labels) : [];

    temp = _.concat(temp, temp1);

    temp.push(
      {
        title: '创建者',
        dataIndex: 'createUsername',
        key: 'createUsername',
        width: 120
      },
      {
        title: '创建时间',
        dataIndex: 'createdTs',
        key: 'createdTs',
        width: 160,
        render: value => {
          return <div>{moment(value).format('YYYY-MM-DD hh:mm:ss')}</div>;
        }
      },
      {
        title: '操作', dataIndex: 'operation', key: 'operation',
        width: 220, fixed: 'right',
        render: (value, record) => {
          return (
            <span>
                    {<a style={{marginRight: '6px'}}
                        onClick={() => this.setState({showDetail: true, record})}
                    >详情</a>}
              {<a style={{marginRight: '6px'}}
                  onClick={() => this.onCreateOrEdit(record)}
              >编辑</a>}
              {<Popconfirm
                title="确认删除"
                onConfirm={() => {
                  this.props.dispatch({
                    type: 'customer/deleteOne',
                    payload: record
                  }).then(res => {
                    this.componentDidMount();
                  });
                }}
                okText="是"
                cancelText="否"
              >
                <a>删除</a>
              </Popconfirm>}
            </span>
          );
        }
      });

    return temp;
  };
  getSearchFields = () => {
    const arr = [
      <FormField
        label="客户编码"
        name="code"
        key={1}
      >
        <Input allowClear placeholder={`请输入${title}编码`}/>
      </FormField>,
      <FormField
        label="客户名称"
        name="name"
        key={2}
      >
        <Input allowClear placeholder={`请输入${title}名称`}/>
      </FormField>
    ];
    return arr;

  };
  onCreateOrEdit = record => {
    const type = record ? 'customer/updateOne' : 'customer/create';
    ModalView.open(ModalCreateOrEditCustomer,
      {
        title,
        width: '920px'
      }, {
        record,
        callback: (payload) => {
          this.props.dispatch({
            type,
            payload
          }).then(res => {
            this.componentDidMount();
          });
        }
      });
  };

  render() {
    const {customers, _notify, form} = this.props;
    if (_notify) {
      notify(_notify);
    }
    const {showDetail, record} = this.state;
    return (
      <Form className={styles.content}>
        <ViewTitle
          title={`${title}列表`}
          level={1}
          actions={[
            <Button type="primary" onClick={() => this.onCreateOrEdit(undefined)}>添加</Button>
            // <Button onClick={() => this.export()}>导出</Button>,
            // <Upload {...uploadprops}>
            // <Button icon={<UploadOutlined/>}>导入</Button>
            // </Upload>
          ]

          }></ViewTitle>
        <SearchForm
          style={{marginLeft: '6px', marginRight: '6px'}}
          onSearch={() => {
            this.state.current = 1;
            this.componentDidMount();
          }}
          onReset={this.handleReset}
          cols={3}
          min={6}
          expandText="展开"
          form={form}
        >
          {this.getSearchFields()}
        </SearchForm>
        <Table
          className={styles.antTable}
          bordered={true}
          columns={this.columns()}
          dataSource={customers}
          scroll={{x: true}}
          pagination={{
            current: this.state.current,
            total: this.state.total,
            showSizeChanger: true,
            onChange: page => {
              this.state.current = page;
              this.componentDidMount();
            },
            onShowSizeChange: (current, pageSize) => {
              this.state.current = 1;
              this.state.pageSize = pageSize;
              this.componentDidMount();
            }
          }}
        ></Table>
        {showDetail && <Drawer
          visible={showDetail}
          title={`${title}详情`}
          placement="left"
          width={'80%'}
          style={{padding: 0}}
          onClose={() => {
            this.setState({showDetail: false});
          }}
        >
          <ModalCustomerDetail
            record={record}
          > </ModalCustomerDetail>
        </Drawer>}

      </Form>
    );
  }
}
